from collections import OrderedDict as _OrderedDict
from rest_framework.serializers import ModelSerializer as _ModelSerializer
from rest_framework.serializers import SerializerMethodField as _SerializerMethodField
from rest_framework.serializers import Serializer as _Serializer

"""
1、继承ModelSerializer，重写to_representation 方法，
2、让其拥有SerializerMethodField可以从钩子获取序列化结果
"""


class BaseSerializer(_Serializer):
    def to_representation(self, instance):
        """
        让序列化和校验，可以在同一个字段中进行，序列化的结果从get_字段中获取结果
        """
        ret = _OrderedDict()
        fields = self._readable_fields
        for field in fields:
            # 判断钩子是否存在，存在就返回钩子的返回值
            if hasattr(self, f"get_{field.field_name}"):
                value = getattr(self, f"get_{field.field_name}")(instance)
                ret[field.field_name] = value
            else:
                attribute = field.get_attribute(instance)
                if attribute is None:
                    ret[field.field_name] = None
                else:
                    ret[field.field_name] = field.to_representation(attribute)
        return ret


class ModelSerializer(BaseSerializer, _ModelSerializer):
    pass


class Serializer(BaseSerializer):
    pass
